#include "SingleLog.h"
#include <QCoreApplication>
#include <QSettings>
#include <qdir.h>
#include <qdatetime.h>
#include <QDirIterator>
#include <qdebug.h>

SingleLog * SingleLog::m_instance = NULL;

SingleLog::SingleLog(QObject *parent) : QObject(parent)
{
    MaxFileSize = 100;
    MaxSaveTime = 30;
    PrintLevel = 3;
    LogDir = "log";
    LogFileName = "Templog.log";
}

SingleLog::~SingleLog()
{

}

void SingleLog::Init()
{
    m_currenDir = QCoreApplication::applicationDirPath();
    QString configFullPath = m_currenDir + "//" + "MSaveLog.ini";

    QFile file(configFullPath);
    QString Dir;
    QString FileName;
    if(file.exists())
    {
        QSettings *configIniRead = new QSettings(configFullPath, QSettings::IniFormat);
        MaxFileSize = configIniRead->value("/Config/MaxFileSize").toInt();
        MaxSaveTime = configIniRead->value("/Config/MaxSaveTime").toInt();
        PrintLevel = configIniRead->value("/Config/PrintLevel").toInt();
        Dir = configIniRead->value("/Config/LogDir").toString();
        FileName = configIniRead->value("/Config/LogFileName").toString();

    }else
    {
        MaxFileSize = 100;
        MaxSaveTime = 30;
        PrintLevel = 3;
        Dir = "log";
        FileName = "Templog.log";
    }

    LogDir = m_currenDir + "//" + Dir;
    LogFileName = LogDir + "//" + FileName;

    QDir dir(LogDir);
    if(!dir.exists())
    {
        dir.mkpath(LogDir);
    }
}

void SingleLog::Printf(int level, const QString strConnect)
{
    QMutexLocker lock(&m_Mutex);

    if(level > PrintLevel || strConnect == lastContent)
    {
        return;
    }

    QDateTime datetime = QDateTime::currentDateTime();

    QString strLevel = "";
    if(level == LEVEL_ERROR){
        strLevel += " ERROR: ";
    }
    else if (level == LEVEL_WARN){
        strLevel += " WARN: ";
    }
    else {
        strLevel += " NORMAL: ";
    }

    QString writeData = datetime.toString("yyyy-MM-dd HH:mm:ss");
    QString strlog = writeData + strLevel + strConnect + "\r\n";

    QFile file(LogFileName);
    if(file.exists())
    {

        file.open(QIODevice::WriteOnly|QIODevice::Append);
        file.write(strlog.toStdString().c_str());
        file.close();

        if(file.size() > 1024 * MaxFileSize)
        {
            QString strTime = datetime.toString("yyyyMMddHHmmss");
            QString newFileName = QString("%1//%2.log").arg(LogDir).arg(strTime);
            file.rename(newFileName);
        }

    }else
    {
        file.open(QIODevice::WriteOnly|QIODevice::Append);
        file.write(strlog.toStdString().c_str());
        file.close();
    }

    Del();
}

void SingleLog::SPrintf(int level, const char *file, const char *func, int lineNum, const char *format,...)
{
    if(level > PrintLevel)
    {
        return;
    }

    va_list vaList;
    char buf[8 * 1024] = {0};
    char outBuf[8 * 1024] = {0};
    int i;
    int len = strlen(file);
    for (i = len - 1; i >= 0; --i)
    {
        if (file[i] == '/' || file[i] == '\\')
        {
            break;
        }
    }

    va_start (vaList, format);
    memset(buf, 0, sizeof(buf));
    vsnprintf(buf, sizeof(buf)-1, format, vaList);
    sprintf(outBuf, "%s:%s():%d,%s", file + i + 1, func, lineNum, buf);

    Printf(level,outBuf);
    va_end(vaList);
}


void SingleLog::Del()
{
    QDir dir(LogDir);
    if(dir.exists())
    {
        QStringList filters;
        filters<<QString("*.log");

        //定义迭代器并设置过滤器
        QDirIterator dir_iterator(LogDir,
                                  filters,
                                  QDir::Files | QDir::NoSymLinks,
                                  QDirIterator::Subdirectories);

        while(dir_iterator.hasNext())
        {
            dir_iterator.next();
            QFileInfo file_info = dir_iterator.fileInfo();

            QDateTime LastModified = file_info.lastModified();
            QDateTime CurrentDataTime = QDateTime::currentDateTime();

            int dateNum = LastModified.daysTo(CurrentDataTime);

            if(dateNum > MaxSaveTime)
            {
                QString fileName = file_info.absoluteFilePath();
                QFile file(fileName);
                file.remove();
            }
        }
    }
}


